package com.test.practice.io.bufferstream;

import lombok.Cleanup;

import java.io.*;

/**
 * 缓冲流 演示
 *
 * @Description: 缓冲流 演示
 * =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class BufferStreamFileCopyDemo {


    public static void main(String[] args) throws Exception {

//        m1();

        m2();

    }

    /**
     * 使用字符流-缓冲流（处理流）实现文件赋值
     * @throws IOException
     */
    private static void m2() throws IOException {
        File srcFile = new File("xxx.txt");
        File dstFile = new File("zzz.txt");

        FileReader fr = new FileReader(srcFile);
        FileWriter fw = new FileWriter(dstFile);

        //关闭外层流，内层流自动关闭
        @Cleanup BufferedReader br = new BufferedReader(fr);
        @Cleanup BufferedWriter bw = new BufferedWriter(fw);

//        方式1：使用字符数组
//        char[] datas = new char[10];
//        int len;
//        while ((len = br.read(datas)) != -1) {
//            bw.write(datas, 0, len);
//        }

        //方式2：使用字符串
        String str;
        while ((str = br.readLine()) != null) {
            //str 中 不包含换行符
            //bw.write(str);
            //方法1：需要自己实现换行符
//            bw.write(str+"\n");

            //方法2：或者使用newLine()
            bw.write(str);
            bw.newLine();
        }
    }

    /**
     * 使用字节流-缓冲流（处理流）实现文件复制
     *
     * @throws IOException
     */
    private static void m1() throws IOException {
        //1.创建File对象
        File srcFile = new File("1.png");
        File dstFile = new File("2.png");

        //2.在File对象基础上 创建节点流
        @Cleanup FileInputStream fis = new FileInputStream(srcFile);
        @Cleanup FileOutputStream fos = new FileOutputStream(dstFile);

        //3.在节点流基础上 创建处理流
        @Cleanup BufferedInputStream bis = new BufferedInputStream(fis);
        @Cleanup BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] datas = new byte[10];
        int len;
        while ((len = bis.read(datas)) != -1) {
            bos.write(datas, 0, len);
        }
    }
}
